<template>
  <div class="cart">
    <Header></Header>
    <div class="main">
      <el-tabs type="border-card">
        <el-tab-pane :label="'全部商品 ' + itemList.length">
          <div class="content">
            <el-table
              ref="multipleTable"
              :data="itemList"
              tooltip-effect="dark"
              style="width: 100%"
              :header-cell-style="{ 'text-align': 'center' }"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
                align="center"
                v-model="checked"
              ></el-table-column>
              <el-table-column label="商品信息" width="300">
                <template slot-scope="scope">
                  <div class="wrapper">
                    <img :src="`http://localhost:8080/api/v1/images/${scope.row.item.imageDir}/thumbnail.jpg`" alt="" />
                    <span>{{ scope.row.item.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="样式" width="300">
                <template slot-scope="scope">{{ scope.row.item.description }}</template>
              </el-table-column>
              <el-table-column label="单价" width="100" align="center">
                <template slot-scope="scope">￥{{ scope.row.item.price | rounding }}</template>
              </el-table-column>
              <el-table-column label="数量" width="240" align="center">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.amountInCart"
                    @change="handleChange(scope.row)"
                    :min="1"
                    :max="scope.row.item.amount"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="总价" width="100" align="center">
                <template slot-scope="scope"
                >￥{{ (scope.row.item.price * scope.row.amountInCart) | rounding }}</template
                >
              </el-table-column>
              <el-table-column show-overflow-tooltip align="center">
                <template slot-scope="scope">
                  <el-button
                    icon="iconfont icon-delete_light"
                    circle
                    @click.native="handleClick(scope.$index, itemList)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="bottom">
              <el-checkbox v-model="checked" style="z-index: 100" @change="handleAll()"
              >全选</el-checkbox
              >
              <span @click="handleClickSpan()">删除</span>
              <div class="bottom-right">
        <span style="right: 400px"
        >已选商品
          <div style="color: #f40">{{ multipleSelection.length }}</div>
          件</span
        >
                <span style="right: 160px"
                >合计（不含运费）：
          <div style="color: #f40">{{ priceTotal | rounding }}</div>
          元</span
                >
              </div>
              <div class="bottom-button" ref="button" @click="buttonIf && toPay()">
                结算
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="'库存紧张 ' + itemListLess.length">
          <CartList :list="itemListLess"></CartList>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import Header from '@/components/Header.vue'
import CartList from '@/components/CartList.vue'

export default {
  components: {
    Header,
    CartList
  },
  data () {
    return {
      itemList: [],
      itemListLess: [],
      multipleSelection: [],
      checked: false,
      priceTotal: 0,
      buttonIf: false
    }
  },
  filters: {
    rounding (val) {
      return val.toFixed(2)
    }
  },
  mounted () {
    this.$http.get('cart', {
      params: {
        userId: JSON.parse(this.$cookie.get('userInfo')).userId
      }
    }).then((res) => {
      if (res.status === 200) {
        this.itemList = res.data
        for (let i = 0; i < this.itemList.length; i++) {
          if (this.itemList[i].item.amount <= 10) {
            this.itemListLess.push(this.itemList[i])
          }
        }
      } else {
        console.log(res)
      }
    }).catch((err) => {
      console.log(err.response)
    })
  },
  computed: {
    listenChange () {
      const { itemList, multipleSelection } = this
      return { itemList, multipleSelection }
    }
  },
  watch: {
    itemList: {
      handler: function () {
        this.handlePriceTotal()
      },
      deep: true
    },
    listenChange () {
      this.handlePriceTotal()
      if (this.multipleSelection.length) {
        this.$refs.button.style = 'background-color:#f40'
        this.buttonIf = true
      } else {
        this.$refs.button.style = 'background-color:#b0b0b0'
        this.buttonIf = false
      }
      if (this.itemList.length) {
        if (this.multipleSelection.length === this.itemList.length) {
          this.checked = true
        } else {
          this.checked = false
        }
      }
    }
  },
  methods: {
    toPay () {
      let list = this.multipleSelection
      const reg1 = new RegExp('amountInCart', 'g')
      const reg2 = new RegExp(',"createdTime":[0-9]*', 'g')
      list = JSON.parse(JSON.stringify(list).replace(reg1, 'amount'))
      list = JSON.parse(JSON.stringify(list).replace(reg2, ''))
      this.$router.push({
        name: 'Pay',
        params: {
          list: list
        }
      })
    },
    handleAll () {
      this.$refs.multipleTable.toggleAllSelection()
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleChange (item) {
      item.priceTotal = item.item.price * item.amountInCart
      this.$http.put('cart', null, {
        params: {
          userId: JSON.parse(this.$cookie.get('userInfo')).userId,
          itemId: item.item.itemId,
          amount: item.amountInCart
        }
      }).then((res) => {
        console.log(res)
      })
    },
    handlePriceTotal () {
      this.priceTotal = 0
      const item = this.multipleSelection
      for (let i = 0; i < item.length; i++) {
        this.priceTotal += item[i].item.price * item[i].amountInCart
      }
    },
    handleClick (index, row) {
      this.$http.delete('cart', {
        params: {
          userId: JSON.parse(this.$cookie.get('userInfo')).userId,
          itemId: row[index].item.itemId
        }
      }).then((res) => {
        console.log(res)
      }).catch((err) => {
        console.log(err.response)
      })
      row.splice(index, 1)
    },
    handleClickSpan () {
      this.itemList = this.itemList.filter(i => !this.multipleSelection.includes(i))
    }
  }
}
</script>

<style lang="less" scoped>
.cart {
  height: 100%;
  overflow: scroll;
  overflow-x: hidden;
  .main {
    width: 80%;
    margin: 0 auto;
    .el-tabs {
      margin-top: 20px;
      /deep/ .el-tabs__nav-scroll {
        background-color: rgb(255, 199, 181);
      }
      /deep/ .el-tabs__item.is-active {
        color: #f40;
        font-size: 20px;
      }
      /deep/ .el-tabs__item:not(.is-disabled):hover {
        color: #f40;
      }
    }
    .content {
      width: 100%;
      .el-table {
        /deep/ .el-table__body tr:hover > td {
          background-color: rgb(248, 225, 217);
        }
        /deep/ .el-checkbox__input.is-checked .el-checkbox__inner,
        .el-checkbox__input.is-indeterminate .el-checkbox__inner {
          background-color: rgb(243, 179, 158);
          border-color: rgb(248, 225, 217);
        }
        .wrapper {
          display: flex;
          img {
            width: 80px;
            height: 80px;
          }
          span {
            padding-left: 10px;
            font-size: 10px;
            flex: 1;
          }
        }
        /deep/ .el-button {
          &:hover {
            background-color: rgb(243, 179, 158);
            color: rgb(236, 89, 40);
            border: none;
          }
          &:focus {
            background-color: #fff;
            color: #606266;
            border: 1px solid #dcdfe6;
          }
        }
      }
      .bottom {
        width: 100%;
        height: 50px;
        background-color: #e5e5e5;
        position: relative;
        .el-checkbox {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          padding: 0 20px;
          /deep/ .el-checkbox__input.is-checked .el-checkbox__inner,
          .el-checkbox__input.is-indeterminate .el-checkbox__inner {
            background-color: #f3b39e;
            border: none;
          }
          /deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
            color: rgb(236, 89, 40);
          }
        }
        span {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          padding-left: 100px;
          color: #606266;
          cursor: pointer;
        }
        .bottom-right {
          span {
            padding-left: 0;
            display: flex;
          }
        }
        .bottom-button {
          width: 100px;
          height: 50px;
          position: absolute;
          right: 0;
          background-color: #b0b0b0;
          font-size: 20px;
          color: white;
          font-weight: bold;
          text-align: center;
          line-height: 50px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
